<?php


namespace App\Http\Model\Job;


use App\Http\Library\Queue;
use Illuminate\Support\Facades\DB;

class PfsHeadQueryAccountBalanceModel
{

    /**
     * 刷新账户余额
     *
     * @param $data
     * @param $result
     *
     * @return bool|int
     * @throws \Exception
     */
    public static function save($data, $result)
    {
        $last = DB::select('SELECT * FROM `pfs_query_account_balance` WHERE `pfs_dw_id`=:pfs_dw_id ORDER BY `id` DESC LIMIT 1', [
            'pfs_dw_id' => $data['pfs_dw_id']
        ]);
        $arr = [
            /*主体*/
            'ledger_subject_id'   => $data['ledger_subject_id'],
            'ledger_subject_name' => $data['ledger_subject_name'],
            /*城市*/
            'city_name'           => $data['city_name'],
            'area_code'           => $data['area_code'],
            'pfs_dw_id'           => $data['pfs_dw_id'],
            'reg_acc_no'          => $result->regAccNo,
            'frozen_amt'          => $result->frozenAmt,
            'transferred_amt'     => $result->transferredAmt,
            'last_end_balance'    => $result->lastEndBalance,
            'utime'               => date('Y-m-d H:i:s'),
        ];
        /*如果记录不存在则创建*/
        if (empty($last)) {
            return DB::table('pfs_query_account_balance')->insert($arr);
        }
        /*几小时生成一条记录*/
        $hour = 6;
        $last = current($last);
        /*
         * 查询是否需要更新最后一条记录
         * 如果最后一条记录的创建时间>指定数据生成周期时间,则执行更新
         * */
        if (strtotime($last->ctime) > strtotime("-{$hour} hour")) {
            return DB::table('pfs_query_account_balance')->where('id', $last->id)->update($arr);
        }
        /*新增一条最新的记录*/
        DB::table('pfs_query_account_balance')->insert($arr);
        /*计算下次任务执行时间*/
        $defer = time() - strtotime(date('Y-m-d H:00:00', strtotime("+{$hour} hour")));
        /*设置定时任务*/
        Queue::clock($data, $defer);
    }

}





/**
 * PfsHeadQueryAccountBalanceModel.php
 *
 * 说明:
 *
 * 修改历史
 * ----------------------------------------
 * 2021/6/9 18:02:00   操作:创建
 **/
